/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.service.impl;

import com.huawei.housekeeper.common.enums.AccountTypeEnum;
import com.huawei.housekeeper.common.enums.ErrorCode;
import com.huawei.housekeeper.common.exception.Assert;
import com.huawei.housekeeper.controller.request.UserLoginDto;
import com.huawei.housekeeper.dao.entity.User;
import com.huawei.housekeeper.dao.mapper.UserMapper;
import com.huawei.housekeeper.service.UserLoginService;
import com.huawei.housekeeper.utils.JwtGenerateTokenUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户登录
 *
 * @author y00464350
 * @since 2022-02-11
 */
@Service
@Qualifier("userDetailsService")
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtGenerateTokenUtil jwtGenerateTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用户登录接口
     *
     * @param userLoginDto 用户登录信息
     * @return token
     */
    @Override
    public String userLogin(UserLoginDto userLoginDto) {
        User user = userMapper.getByUserName(userLoginDto.getUserName());
        Assert.isFalse(user == null, ErrorCode.USER_EMPTY.getCode(), ErrorCode.USER_EMPTY.getMessage());
        // 校验登录角色类型
        AccountTypeEnum typeEnum = AccountTypeEnum.ofAccountType(userLoginDto.getAccountType())
                .orElseGet(() -> AccountTypeEnum.ACCOUNT_USER);
        Assert.isTrue(user.getAccountType() == typeEnum.getCode(),
                ErrorCode.USER_EMPTY.getCode(), ErrorCode.USER_EMPTY.getMessage());
        String password = user.getPassword();
        // 校验密码
        Assert.isTrue(passwordEncoder.matches(userLoginDto.getPassword(), password),
                ErrorCode.USERNAME_OR_PASSWORD_ERROR.getCode(), ErrorCode.USERNAME_OR_PASSWORD_ERROR.getMessage());

        return jwtGenerateTokenUtil.generateToken(user);
    }

}
